package middleware

import (
	"context"

	"gitee.com/mkwchecking/sr-core/storage/cache"
	"gitee.com/mkwchecking/sr-core/yerr"
	"github.com/gin-gonic/gin"
)

const (
	CacheMiddleKey = "cache"
)

func WithCache(ctx context.Context) (gin.HandlerFunc, error) {
	cacheSet, ok := cache.FromCtx(ctx)
	if !ok {
		return nil, yerr.ErrBizPluginNotFound.Error("cache")
	}

	return func(ctx *gin.Context) {
		ctx.Set(CacheMiddleKey, cacheSet)
		ctx.Next()
	}, nil
}

func GetCacheSet(ctx *gin.Context) (cache.ICacheSet, error) {

	if cacheSet, ok := ctx.Get(CacheMiddleKey); ok {
		if cs, ok := cacheSet.(cache.ICacheSet); ok {
			return cs, nil
		}
	}

	return nil, yerr.ErrBizPluginNotFound.Error("cache")
}
